Imports System.Configuration
Imports System.Web.Configuration
Imports nFlickrViewer
Imports ColorPickerTest
Imports FlickrNet
Imports System.IO


Partial Public Class Admin
    Inherits System.Web.UI.Page

    Private isAdmin As Boolean
    'Private Shared configurationSection As nFlickrViewerConfigurationSection = ConfigurationManager.GetSection("nFlickrViewer")
    Private Shared config As nFlickrViewerConfigurationSection = ConfigurationManager.GetSection("nFlickrViewer")
    Private Shared configSectionFlickr As FlickrConfigurationElement = config.FlickrConfigurationElement
    Private Shared configSectionSimple As SimpleViewerConfigurationElement = config.SimpleViewerConfigurationElement
    Private Shared flickr As FlickrNet.Flickr


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        If Not IsPostBack Then
            pnlLogin.Visible = True
            pnlConfig.Visible = False
            pnlChangePassword.Visible = False
            pnlButtons.Visible = False
            'pnlConfigFlickrApiKey.Visible = False
          
        End If
       

        ' Response.Write(configurationSection.FlickrConfigurationElement.flickrApiKey)
    End Sub


    Private Sub SaveAllConfigEntries()
        Try
            ' If isAdmin = True Then
            flickr = New Flickr(txtFlickrApiKey.Text.Trim())

            Dim webConfig As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
            Dim webConfigSection As nFlickrViewerConfigurationSection = webConfig.GetSection("nFlickrViewer")

            webConfigSection.LockItem = False
            If webConfigSection.IsReadOnly() = False And webConfigSection.SectionInformation.IsLocked = False Then


                webConfigSection.FlickrConfigurationElement.flickrApiKey = txtFlickrApiKey.Text.Trim()
                webConfigSection.FlickrConfigurationElement.runningMode = ddlrunningMode.SelectedValue
                webConfigSection.FlickrConfigurationElement.flickrSetId = ddlFlickrSet.SelectedValue
                webConfigSection.FlickrConfigurationElement.flickrTag = txtFlickrTag.Text

                Dim user As FoundUser = flickr.PeopleFindByUsername(txtFlickrUserName.Text.Trim())

                webConfigSection.FlickrConfigurationElement.flickrUserId = user.UserId

                webConfigSection.FlickrConfigurationElement.flickrSearchTerm = txtFlickrSearchTerm.Text.Trim()

                webConfigSection.FlickrConfigurationElement.flickrImageSize = ddlFlickrImageSize.SelectedValue

                webConfigSection.FlickrConfigurationElement.flickrGroupId = ddlFlickrGroup.SelectedValue

                webConfigSection.FlickrConfigurationElement.flickrStaticImageUrl = txtFlickrStaticImageUrl.Text.Trim()

                If Not String.IsNullOrEmpty(txtFlickrMaxNoResults.Text.Trim()) Then
                    webConfigSection.FlickrConfigurationElement.flickrMaxNoResults = CType(txtFlickrMaxNoResults.Text, Integer)
                End If
                webConfigSection.FlickrConfigurationElement.flickrSortOrder = ddlFlickrSortOrder.SelectedValue

                If Not String.IsNullOrEmpty(txtFlickrCacheInterval.Text.Trim()) Then
                    webConfigSection.FlickrConfigurationElement.flickrCacheInterval = CType(txtFlickrCacheInterval.Text, Integer)
                Else
                    webConfigSection.FlickrConfigurationElement.flickrCacheInterval = 0

                End If


                'save all simpleviewer config
                If Not String.IsNullOrEmpty(txtMaxImageHeight.Text.Trim()) Then
                    webConfigSection.SimpleViewerConfigurationElement.maxImageWidth = txtMaxImageHeight.Text.Trim()
                End If

                If Not String.IsNullOrEmpty(txtMaxImageHeight.Text.Trim()) Then
                    webConfigSection.SimpleViewerConfigurationElement.maxImageWidth = txtMaxImageHeight.Text.Trim()
                End If

                If Not String.IsNullOrEmpty(txtMaxImageHeight.Text.Trim()) Then
                    webConfigSection.SimpleViewerConfigurationElement.maxImageWidth = txtMaxImageHeight.Text.Trim()
                End If


                webConfigSection.SimpleViewerConfigurationElement.thumbnailColumns = ddlThumbnailColumns.SelectedValue
                webConfigSection.SimpleViewerConfigurationElement.thumbnailRows = ddlThumbnailRows.SelectedValue

                webConfigSection.SimpleViewerConfigurationElement.navDirection = ddlNavDirection.SelectedValue
                webConfigSection.SimpleViewerConfigurationElement.navPosition = ddlNavPosition.SelectedValue

                webConfigSection.SimpleViewerConfigurationElement.textColor = cpTextColor.SelectedHexValue
                webConfigSection.SimpleViewerConfigurationElement.frameColor = cpFrameColor.SelectedHexValue

                webConfigSection.SimpleViewerConfigurationElement.frameWidth = txtFrameWidth.Text.Trim()
                webConfigSection.SimpleViewerConfigurationElement.stagePadding = txtStagePadding.Text.Trim()

                webConfigSection.SimpleViewerConfigurationElement.galleryTitle = txtgalleryTitle.Text.Trim()
                webConfigSection.SimpleViewerConfigurationElement.backgroundImagePath = txtBackgroundImagePath.Text.Trim()

                webConfigSection.SimpleViewerConfigurationElement.enableRightClickOpen = chkenableRightClickOpen.Checked
                webConfigSection.SimpleViewerConfigurationElement.includeImageName = chkincludeImageName.Checked
                webConfigSection.SimpleViewerConfigurationElement.includeImageLink = chkincludeImageLink.Checked
                webConfigSection.SimpleViewerConfigurationElement.includePaypalLink = chkincludePaypalLink.Checked

                webConfigSection.SimpleViewerConfigurationElement.contactMeEmailAddress = txtcontactMeEmailAddress.Text.Trim()
                webConfigSection.SimpleViewerConfigurationElement.paypalCartLink = txtpaypalCartLink.Text.Trim()
                webConfigSection.SimpleViewerConfigurationElement.paypalEmailAddress = txtpaypalEmailAddress.Text.Trim()

                If Not String.IsNullOrEmpty(txtpaypalPricePerItem.Text.Trim()) Then
                    webConfigSection.SimpleViewerConfigurationElement.paypalPricePerItem = txtpaypalPricePerItem.Text.Trim()
                Else
                    webConfigSection.SimpleViewerConfigurationElement.paypalPricePerItem = 0
                End If

                webConfig.Save()

                'delete cached xml
                If System.IO.File.Exists(HttpContext.Current.Server.MapPath("flickrData.xml")) Then
                    System.IO.File.Delete(HttpContext.Current.Server.MapPath("flickrData.xml"))
                End If
            End If


        Catch ex As FlickrException
            'Throw ex validator should catch
        Catch ee As Exception
            Throw ee
        End Try

        lblError.Text = "Saved!"


    End Sub

    Private Sub LoadFlickrData()
        If isAdmin = True Then
            Try


                flickr = New Flickr(configSectionFlickr.flickrApiKey)

                Dim person As Person = flickr.PeopleGetInfo(configSectionFlickr.flickrUserId)

                Dim user As FoundUser = flickr.PeopleFindByUsername(person.UserName)

                'populate your flickr sets
                Dim sets As Photosets = flickr.PhotosetsGetList(user.UserId)
                For Each s As Photoset In sets.PhotosetCollection
                    ddlFlickrSet.Items.Add(New ListItem(s.Title, s.PhotosetId))
                Next


                'populate your flickr sets
                Dim groups As PublicGroupInfo() = flickr.PeopleGetPublicGroups(user.UserId)
                For Each g As PublicGroupInfo In groups
                    ddlFlickrGroup.Items.Add(New ListItem(g.GroupName, g.GroupId))
                Next
                'populate your flickr groups

                ddlFlickrSortOrder.Items.Add("DatePostedAsc")
                ddlFlickrSortOrder.Items.Add("DatePostedDesc")
                ddlFlickrSortOrder.Items.Add("DateTakenAsc")
                ddlFlickrSortOrder.Items.Add("DateTakenDesc")
                ddlFlickrSortOrder.Items.Add("InterestingnessAsc")
                ddlFlickrSortOrder.Items.Add("InterestingnessDesc")
                ddlFlickrSortOrder.Items.Add("None")
                ddlFlickrSortOrder.Items.Add("Relevance")


            Catch ex As FlickrException
                'pnlConfig.Visible = False
                'pnlConfigFlickrApiKey.Visible = True
                'lblError.Text = "Invalid Flickr API key"
            End Try

        End If



    End Sub
    Private Sub LoadAllConfigEntries()
        If isAdmin = True Then
            Try

      
                flickr = New Flickr(configSectionFlickr.flickrApiKey)
                txtFlickrApiKey.Text = configSectionFlickr.flickrApiKey
                ddlrunningMode.SelectedIndex = -1
                ddlrunningMode.Items.FindByValue(configSectionFlickr.runningMode).Selected = True

                ddlFlickrSet.SelectedIndex = -1
                If ddlFlickrSet.Items.Contains(ddlFlickrSet.Items.FindByValue(configSectionFlickr.flickrSetId)) Then
                    ddlFlickrSet.Items.FindByValue(configSectionFlickr.flickrSetId).Selected = True
                End If

                txtFlickrTag.Text = configSectionFlickr.flickrTag
                Dim person As Person = flickr.PeopleGetInfo(configSectionFlickr.flickrUserId)
                If Not person Is Nothing Then
                    txtFlickrUserName.Text = person.UserName
                End If


                txtFlickrSearchTerm.Text = configSectionFlickr.flickrSearchTerm

                ddlFlickrImageSize.SelectedIndex = -1
                If ddlFlickrImageSize.Items.Contains(ddlFlickrImageSize.Items.FindByValue(configSectionFlickr.flickrImageSize)) Then
                    ddlFlickrImageSize.Items.FindByValue(configSectionFlickr.flickrImageSize).Selected = True
                End If


                ddlFlickrGroup.SelectedIndex = -1
                If ddlFlickrGroup.Items.Contains(ddlFlickrGroup.Items.FindByValue(configSectionFlickr.flickrGroupId)) Then
                    ddlFlickrGroup.Items.FindByValue(configSectionFlickr.flickrGroupId).Selected = True
                End If

                txtFlickrStaticImageUrl.Text = configSectionFlickr.flickrStaticImageUrl
                txtFlickrMaxNoResults.Text = configSectionFlickr.flickrMaxNoResults
                txtflickrCacheInterval.Text = configSectionFlickr.flickrCacheInterval

                ddlFlickrSortOrder.SelectedIndex = -1
                If ddlFlickrSortOrder.Items.Contains(ddlFlickrSortOrder.Items.FindByValue(configSectionFlickr.flickrSortOrder)) Then
                    ddlFlickrSortOrder.Items.FindByValue(configSectionFlickr.flickrSortOrder).Selected = True
                End If

                'load all simpleviewer config
                txtMaxImageHeight.Text = configSectionSimple.maxImageHeight
                txtMaxImageWidth.Text = configSectionSimple.maxImageWidth

                ddlThumbnailColumns.SelectedIndex = -1
                If ddlThumbnailColumns.Items.Contains(ddlThumbnailColumns.Items.FindByValue(configSectionSimple.thumbnailColumns)) Then
                    ddlThumbnailColumns.Items.FindByValue(configSectionSimple.thumbnailColumns).Selected = True
                End If

                ddlThumbnailRows.SelectedIndex = -1
                If ddlThumbnailRows.Items.Contains(ddlThumbnailRows.Items.FindByValue(configSectionSimple.thumbnailRows)) Then
                    ddlThumbnailRows.Items.FindByValue(configSectionSimple.thumbnailRows).Selected = True
                End If

                ddlNavDirection.SelectedIndex = -1
                If ddlNavDirection.Items.Contains(ddlNavDirection.Items.FindByValue(configSectionSimple.navDirection)) Then
                    ddlNavDirection.Items.FindByValue(configSectionSimple.navDirection).Selected = True
                End If

                ddlNavPosition.SelectedIndex = -1
                If ddlNavPosition.Items.Contains(ddlNavPosition.Items.FindByValue(configSectionSimple.navPosition)) Then
                    ddlNavPosition.Items.FindByValue(configSectionSimple.navPosition).Selected = True
                End If

                cpTextColor.SelectedHexValue = configSectionSimple.textColor
                cpFrameColor.SelectedHexValue = configSectionSimple.frameColor

                txtFrameWidth.Text = configSectionSimple.frameWidth
                txtStagePadding.Text = configSectionSimple.stagePadding

                txtgalleryTitle.Text = configSectionSimple.galleryTitle
                txtBackgroundImagePath.Text = configSectionSimple.backgroundImagePath

                chkenableRightClickOpen.Checked = configSectionSimple.enableRightClickOpen
                chkincludeImageName.Checked = configSectionSimple.includeImageName
                chkincludeImageLink.Checked = configSectionSimple.includeImageLink
                chkincludePaypalLink.Checked = configSectionSimple.includePaypalLink

                txtcontactMeEmailAddress.Text = configSectionSimple.contactMeEmailAddress
                txtpaypalCartLink.Text = configSectionSimple.paypalCartLink
                txtpaypalEmailAddress.Text = configSectionSimple.paypalEmailAddress

                txtpaypalPricePerItem.Text = configSectionSimple.paypalPricePerItem




            Catch ex As FlickrException
                'Throw ex
            Catch e As Exception
                Throw e
            End Try
        End If
    End Sub
    Protected Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
        If txtPassword.Text.Trim() = config.AdminConfigurationElement.password Then
            isAdmin = True
            lblError.Text = ""
            'Response.Write("you are the admin")
            pnlLogin.Visible = False
            If txtPassword.Text.Trim() = "password" Then
                pnlChangePassword.Visible = True
                pnlConfig.Visible = False
                pnlButtons.Visible = False
            Else
                pnlConfig.Visible = True
                pnlChangePassword.Visible = False
                pnlButtons.Visible = True
                LoadFlickrData()
                LoadAllConfigEntries()
            End If



        Else
            isAdmin = False
            'lblError.Text = "Login Incorrect."
            'Response.Write("you are not the admin")
        End If
    End Sub


    Protected Sub btnChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnChangePassword.Click

        pnlChangePassword.Visible = True
        pnlConfig.Visible = False
        pnlButtons.Visible = False
    End Sub
    Protected Sub btnSubmitChangePassword_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmitChangePassword.Click
        If txtOldPassword.Text.Trim() = config.AdminConfigurationElement.password And txtNewPassword2.Text.Trim() = txtNewPassword2.Text.Trim() Then
            'save new password
            Dim webConfig As Configuration = WebConfigurationManager.OpenWebConfiguration("~")
            Dim webConfigSection As nFlickrViewerConfigurationSection = webConfig.GetSection("nFlickrViewer")
            webConfigSection.LockItem = False
            If webConfigSection.IsReadOnly() = False And webConfigSection.SectionInformation.IsLocked = False Then
                webConfigSection.AdminConfigurationElement.password = txtNewPassword2.Text.Trim()

                webConfig.Save()
            End If
            isAdmin = True
            pnlChangePassword.Visible = False
            pnlConfig.Visible = True
            pnlButtons.Visible = True
            LoadFlickrData()
            LoadAllConfigEntries()

        Else
            isAdmin = False
        End If
    End Sub


    Public Sub ValidateFlickrApiKey(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = True
        Try
            ' If isAdmin = True Then
            flickr = New Flickr(txtFlickrApiKey.Text.Trim())
            'Dim person As Person = flickr.PeopleGetInfo(configSectionFlickr.flickrUserId)
            'Dim user As FoundUser = flickr.TestLogin()
            'Dim b As Boolean = flickr.IsAuthenticated()
            Dim user As FoundUser = flickr.PeopleFindByUsername("luzer") ' for now
            Dim b As Boolean = flickr.IsAuthenticated()
            If user Is Nothing Then
                args.IsValid = False
            End If

            'flickr.TestLogin()
        Catch ex As FlickrException
            args.IsValid = False
        End Try



    End Sub


    Public Sub ValidatePassword(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = True
        Try
            If Not args.Value.Trim() = config.AdminConfigurationElement.password Then

                args.IsValid = False
            End If
        Catch ex As Exception
            args.IsValid = False
        End Try



    End Sub
    Public Sub ValidateFlickrUsername(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
        args.IsValid = True
        Try
            ' If isAdmin = True Then
            flickr = New Flickr(txtFlickrApiKey.Text.Trim())
            Dim user As FoundUser = flickr.PeopleFindByUsername(txtFlickrUserName.Text.Trim()) ' (configSectionFlickr.flickrUserId)
            Dim b As Boolean = flickr.IsAuthenticated()
            If user Is Nothing Then
                args.IsValid = False
            End If
            'flickr.TestLogin()
        Catch ex As FlickrException
            args.IsValid = False
        End Try



    End Sub
    Protected Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        SaveAllConfigEntries()

    End Sub
    Protected Sub btnCancelPasswordChange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancelChangePassword.Click

        pnlChangePassword.Visible = False
        pnlConfig.Visible = True
        pnlButtons.Visible = True
    End Sub
    Private Sub btnCancelChangePassword_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancelChangePassword.Click

    End Sub
End Class